<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let p1 = new Promise((res) => {
        setTimeout(() => {
          res(111);
        }, 1000);
      });
      let p2 = new Promise((res, rej) => {
        setTimeout(() => {
          rej(2222);
        }, 3000);
      });

      let p3 = new Promise((res) => {
        setTimeout(() => {
          res(333);
        }, 2000);
      });
      // Promise.all([p1,p2,p3]).then(res=>{})
      //   function myAll(arr) {
      //     return new Promise((resolve, reject) => {
      //       let resArr = [];
      //       let count = 0;
      //       arr.forEach((item) => {
      //         item.then(
      //           (res) => {
      //             resArr.push(res);
      //             // 什么时候证明结果全部收集完毕；
      //             count++;
      //             if (count == arr.length) {
      //               // 所有的promise对象的结果收集完毕 ；
      //               resolve(resArr);
      //             }
      //           },
      //           (err) => {
      //             reject(err);
      //           }
      //         );
      //       });
      //     });
      //   }
      //   myAll([p1, p2, p3]).then((res) => {
      //     console.log(res);
      //   });
      // Promise.allSettled([p1,p2,p3]).then(res=>{})
      myallSettled([p1, p2, p3]).then((res) => {
        console.log(res);
      });
      function myallSettled(arr) {
        return new Promise((resolve) => {
          let count = 0;
          let resArr = new Array(arr.length); // [empty,empty,empty];
          arr.forEach((item) => {
            item.then(
              (res) => {
                let obj = {
                  status: "fufilled",
                  value: res,
                };
                resArr[count] = obj;
                count++;
                if (count == arr.length) {
                  resolve(resArr);
                }
              },
              (err) => {
                let obj = {
                  status: "rejected",
                  error: err,
                };
                resArr[count] = obj;
                count++;
                if (count == arr.length) {
                  resolve(resArr);
                }
              }
            );
          });
        });
      }
    </script>
  </body>
</html>
